package com.flame.core.config;

import com.flame.core.id.IdWorker;
import com.flame.core.mybatis.FlamePageInterceptor;
import com.flame.core.web.FlameWebCoreFilter;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import javax.annotation.PostConstruct;
import java.security.Security;

@ComponentScan("com.flame.core")
@Configurable
public class CoreConfiguration {

    @ConditionalOnMissingBean(IdWorker.class)
    @Bean
    public IdWorker idWorker() {
        return new IdWorker(null);
    }

    @Configuration
    @ConditionalOnClass({SqlSessionFactory.class})
    protected static class MybatisConfiguration {

        @Bean
        @Order(Integer.MAX_VALUE - 10)
        public PageInterceptor pageInterceptor() {
            return new PageInterceptor();
        }

        @Bean
        @Order(Integer.MAX_VALUE)
        public FlamePageInterceptor pageAdvice() {
            return new FlamePageInterceptor();
        }
    }

    @Bean
    public FilterRegistrationBean flameWebCoreFilterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setName("flameWebCoreFilter");
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.setOrder(Ordered.LOWEST_PRECEDENCE);
        filterRegistrationBean.setFilter(new FlameWebCoreFilter());
        return filterRegistrationBean;
    }
}
